. "$PSScriptRoot/common.ps1"

foreach ($projPath in $projects) {
    try {
        $csproj = Get-ChildItem -Path "$rootFolder/$projPath" -Filter "Jy.Abp.*.csproj" | Select-Object -First 1
        if ($csproj) {
            $projName = [System.IO.Path]::GetFileNameWithoutExtension($csproj.Name)
            $newPkgId = Get-PackageId -projectName $projName

            $xml = [xml](Get-Content $csproj.FullName)
            # 查找第一个包含TargetFrameworks的PropertyGroup
            $pg = $xml.Project.PropertyGroup | Where-Object { $_.TargetFrameworks } | Select-Object -First 1
            
            if ($pg) {
                if ($pg.PackageId) {
                    $pg.PackageId = $newPkgId
                } else {
                    $pkgIdElem = $xml.CreateElement("PackageId")
                    $pkgIdElem.InnerText = $newPkgId
                    $pg.AppendChild($pkgIdElem) | Out-Null
                }
                $xml.Save($csproj.FullName)
                Write-Host "已处理 $($csproj.FullName) => $newPkgId" -ForegroundColor Green
            } else {
                # 如果没有找到合适的PropertyGroup，创建一个新的
                $newPg = $xml.CreateElement("PropertyGroup")
                $pkgIdElem = $xml.CreateElement("PackageId")
                $pkgIdElem.InnerText = $newPkgId
                $newPg.AppendChild($pkgIdElem) | Out-Null
                $xml.Project.AppendChild($newPg) | Out-Null
                $xml.Save($csproj.FullName)
                Write-Host "已追加并处理 $($csproj.FullName) => $newPkgId" -ForegroundColor Green
            }
        } else {
            Write-Host "警告: 未找到项目文件 $projPath" -ForegroundColor Yellow
        }
    }
    catch {
        Write-Host "错误: 处理 $projPath 时发生异常: $_" -ForegroundColor Red
    }
}

Write-Host "`n包名更新完成！" -ForegroundColor Cyan 